import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {InterviewerService, QuestionService} from '../../function/app.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {checkEmail, checkPhoneNumber} from '../../function/validators';
import {HttpParams} from '@angular/common/http';

@Component({
  selector: 'app-mult-test',
  templateUrl: './mult-test.component.html',
  styleUrls: ['./mult-test.component.scss']
})
export class MultTestComponent implements OnInit {
  registerForm: FormGroup;
  questions: any[];
  infoTag = false;
  result = {};

  constructor(private builder: FormBuilder,
              private questionService: QuestionService,
              private nzModel: NzModalService,
              private nzMessage: NzMessageService,
              private interviewerService: InterviewerService) {
    this.registerForm = this.builder.group({
      user_name: ['', Validators.required],
      email: ['', checkEmail],
      phone_number: ['', checkPhoneNumber],
    });
  }

  ngOnInit() {
    this.questionService.get('', {
      observe: 'response',
      params:
        new HttpParams()
          .set('type', '1')
    }).subscribe((resp: any) => {
      this.questions = resp.body;
    });
  }

  startTest() {
    if (this.registerForm.valid) {
      this.infoTag = true;
    }
  }

  chooseYes(event: any, data: any, index: number) {
    if (event) {
      this.result[index] = data;
    }
  }

  commit() {
    if (Object.keys(this.result).length !== 144) {
      this.nzMessage.error('请做完所有题目');
      return;
    }
    const resultList = [];
    // tslint:disable-next-line:forin
    for (const key in this.result) {
      resultList.push(this.result[key]);
    }
    const resultCount = resultList.reduce((allNames, name) => {
      if (name in allNames) {
        allNames[name]++;
      } else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    this.registerForm.value.answer = JSON.stringify(resultCount);
    this.interviewerService.post('', this.registerForm.value).subscribe((resp) => {
      this.nzModel.success(
        {
          nzTitle: '提交成功',
          nzContent: '测试提交成功，请联系管理员！',
        }
      );
    }, () => {
      this.nzMessage.error('请勿重复提交！');
    });
  }
}
